package top.rufous.hrm.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import top.rufous.hrm.query.EmpQuery;
import top.rufous.hrm.service.IEmpService;
import top.rufous.hrm.domain.Emp;

import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.rufous.hrm.util.AjaxResult;
import top.rufous.hrm.util.PageList;

import java.util.List;

@RestController
@RequestMapping("/emp")
public class EmpController {
    @Autowired
    public IEmpService empService;


    /**
     * 保存和修改公用的
     * @param emp  传递的实体
     * @return Ajaxresult转换结果
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Emp emp){
        try {
            if( emp.getId()!=null)
                empService.updateById(emp);
            else
                empService.insert(emp);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("保存对象失败！"+e.getMessage());
        }
    }
    /**
    * 删除对象信息
    * @param id
    * @return
    */
    @DeleteMapping(value="/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            empService.deleteById(id);
            return AjaxResult.me();
        } catch (Exception e) {
        e.printStackTrace();
            return AjaxResult.me().setMessage("删除对象失败！"+e.getMessage());
        }
    }
	
    //获取用户
    @GetMapping("/{id}")
    public Emp get(@PathVariable("id")Long id)
    {
        return empService.selectById(id);
    }


    /**
    * 查看所有的员工信息
    * @return
    */
    @GetMapping()
    public List<Emp> list(){

        return empService.selectList(null);
    }


    /**
    * 分页查询数据
    *
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping("/list")
    public PageList<Emp> json(@RequestBody EmpQuery query)
    {
        Page<Emp> page = new Page<Emp>(query.getPage(),query.getRows());
        //page = empService.selectPage(page);
        // 高级分页查询
        EntityWrapper<Emp> wrapper = new EntityWrapper<>();
        wrapper.like("name",query.getKeyword())
        .and()
        .le("age",30);
        empService.selectPage(page,wrapper);
        return new PageList<Emp>(page.getTotal(),page.getRecords());
    }
}
